package com.gdkj.util;

import com.alibaba.fastjson.JSONObject;
import com.tencentcloudapi.ame.v20190916.AmeClient;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.trtc.v20190722.TrtcClient;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.LocalDateTime;
import java.time.ZoneOffset;

public class TencentUtil {

    private TencentUtil() {

    }

    private static AmeClient ameClient = null;

    private static TrtcClient trtcClient = null;

    public static AmeClient getAmeClient() {
        if (ameClient == null) {
            // 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey,此处还需注意密钥对的保密
            // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
            Credential cred = new Credential("AKIDgGeokRu88tQimbBXeW8VbR1MRHrCH6fy", "6wW4FBsKYXHm23pMehW6RYWAZjeKl77s");
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("ame.tencentcloudapi.com");
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            ameClient = new AmeClient(cred, "", clientProfile);
        }

        return ameClient;
    }

    public static TrtcClient getTrtcClient() {
        if (trtcClient == null) {
            // 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey,此处还需注意密钥对的保密
            // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
            Credential cred = new Credential("AKIDgGeokRu88tQimbBXeW8VbR1MRHrCH6fy", "6wW4FBsKYXHm23pMehW6RYWAZjeKl77s");
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("trtc.tencentcloudapi.com");
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            trtcClient = new TrtcClient(cred, "ap-guangzhou", clientProfile);
        }

        return trtcClient;
    }

    /**
     * 获取推流或者拉流地址
     *
     * @param privateConfig
     * @param stream
     * @param type
     * @return java.lang.String
     */
    public static String getPushAndPullAddress(JSONObject privateConfig, String stream, Integer type) {
        String url;
        String bizId = privateConfig.getString("tx_bizid");
        String pushUrlKey = privateConfig.getString("tx_push_key");
        String push = privateConfig.getString("tx_push");
        String pull = privateConfig.getString("tx_pull");

        LocalDateTime localDateTime = LocalDateTime.now();
        LocalDateTime localDateTimeNew = localDateTime.plusDays(1);
        long timestampNew = localDateTimeNew.toEpochSecond(ZoneOffset.of("+8"));

        String safeUrl = getSafeUrl(pushUrlKey, stream, timestampNew);
        if (type == 1) {
            url = String.format("rtmp://%s/live/%s?bizid=%s&%s", push, stream, bizId, safeUrl);
        } else {
            url = String.format("http://%s/live/%s.flv", pull, stream);
        }
        return url;
    }


    public static String getPushAndPullAddressWeb(JSONObject privateConfig, String stream, Integer type) {
        String bizId = privateConfig.getString("tx_bizid");
        String pushUrlKey = privateConfig.getString("tx_push_key");
        String push = privateConfig.getString("tx_push");
        String pull = privateConfig.getString("tx_pull");
        LocalDateTime localDateTime = LocalDateTime.now();
        LocalDateTime localDateTimeNew = localDateTime.plusDays(1L);
        long timestampNew = localDateTimeNew.toEpochSecond(ZoneOffset.of("+8"));
        String safeUrl = getSafeUrl(pushUrlKey, stream, timestampNew);
        String url;
        if (type == 1) {
            url = String.format("webrtc://%s/live/%s?bizid=%s&%s", push, stream, bizId, safeUrl);
        } else {
            url = String.format("http://%s/live/%s.flv", pull, stream);
        }

        return url;
    }


    private static final char[] DIGITS_LOWER = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    /*
     * KEY+ streamName + txTime
     */
    private static String getSafeUrl(String key, String streamName, long txTime) {
        String input = key + streamName + Long.toHexString(txTime).toUpperCase();
        String txSecret = null;
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            txSecret = byteArrayToHexString(messageDigest.digest(input.getBytes(StandardCharsets.UTF_8)));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return txSecret == null ? "" : "txSecret=" + txSecret + "&" + "txTime=" + Long.toHexString(txTime).toUpperCase();
    }

    private static String byteArrayToHexString(byte[] data) {
        char[] out = new char[data.length << 1];

        for (int i = 0, j = 0; i < data.length; i++) {
            out[j++] = DIGITS_LOWER[(0xF0 & data[i]) >>> 4];
            out[j++] = DIGITS_LOWER[0x0F & data[i]];
        }
        return new String(out);
    }
}
